// import {login, webLogin} from '@/api/user.js'
const TOKEN = 'token'
const refreshToken = 'refreshToken'
const EXPIRES = 'expires'
const USER_INFO_KEY = 'userInfo'
export default {
	namespaced: true,
	state: () => {
		return {
			token: uni.getStorageSync(TOKEN) || '',
			expires: uni.getStorageSync(EXPIRES) || '',
			refreshToken: uni.getStorageSync(refreshToken) || '',
			userInfo: uni.getStorageSync(USER_INFO_KEY) || {},
		}
	},
	mutations: {
		removeToken(state) {
			state.token = ''
			state.expires = ''
			state.refreshToken = ''
			this.commit('user/saveToToken')
		},
		removeUserInfo(state) {
			state.userInfo = {}
			this.commit('user/saveToUserInfo')
		},
		saveToToken(state) {
			uni.setStorage({
				key: TOKEN,
				data: state.token
			})
			uni.setStorage({
				key: refreshToken,
				data: state.refreshToken
			})
			uni.setStorage({
				key: EXPIRES,
				data: state.expires
			})
		},
		saveToUserInfo(state) {
			uni.setStorage({
				key:USER_INFO_KEY,
				data: state.userInfo
			})
		},
		setToken(state,token) {
			state.token = token
			this.commit('user/saveToToken')
		},
		setRefreshToken(state,token) {
			state.refreshToken = token
			this.commit('user/saveToToken')
		},
		setExpires(state,expires) {
			state.expires = expires
			this.commit('user/saveToToken')
		},
		setUserInfo(state,userInfo) {
			state.userInfo = userInfo
			this.commit('user/saveToUserInfo')
		}
	},
	actions: {
		/**
		 * 退出登录
		 */
		logout(context) {
			this.commit('user/removeToken')
			this.commit('user/removeUserInfo')
		},
		isLogin(context) {
			if (context.state.token) {
				return true
			} else {				
				return false
			}
		},
		/**
		 * 修改用户信息
		 * @param {Object} context
		 * @param {Object} userProfile
		 */
		update(context,userInfo) {
			this.commit('user/setUserInfo',userInfo)
		},
		/**
		 * 用户登录
		 */
		async login(context,userProfile) {
			let userInfo = {
				name: userProfile.username,
			}
			const expires = new Date(userProfile.expires).getTime()
			this.commit('user/setToken',userProfile.accessToken)
			this.commit('user/setRefreshToken',userProfile.refreshToken)
			this.commit('user/setExpires',expires)
			this.commit('user/setUserInfo',userInfo)
			return userInfo
		}
	}
}